#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Matplotlib字体缓存构建脚本
在打包应用程序前运行此脚本，预先构建字体缓存
"""

import os
import sys
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def main():
    """主函数"""
    # 配置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    logger = logging.getLogger("build_font_cache")
    logger.info("开始构建Matplotlib字体缓存...")
    
    try:
        # 导入matplotlib
        import matplotlib
        # 设置使用Agg后端
        matplotlib.use('Agg')
        
        # 强制重建字体缓存
        from matplotlib import font_manager
        font_manager._rebuild()
        
        # 检查缓存文件是否存在
        cache_dir = matplotlib.get_cachedir()
        fontlist_path = os.path.join(cache_dir, 'fontlist-v330.json')
        
        if os.path.exists(fontlist_path):
            logger.info(f"字体缓存文件已创建: {fontlist_path}")
            logger.info(f"文件大小: {os.path.getsize(fontlist_path)} 字节")
            
            # 创建缓存文件的副本到打包目录
            font_cache_dir = project_root / "assets" / "matplotlib_cache"
            os.makedirs(font_cache_dir, exist_ok=True)
            
            import shutil
            target_path = os.path.join(font_cache_dir, os.path.basename(fontlist_path))
            shutil.copy2(fontlist_path, target_path)
            
            logger.info(f"字体缓存文件已复制到: {target_path}")
            
        else:
            logger.error(f"字体缓存文件未创建: {fontlist_path}")
            
        logger.info("Matplotlib字体缓存构建完成")
        
    except Exception as e:
        logger.error(f"构建字体缓存失败: {e}", exc_info=True)
        return 1
        
    return 0

if __name__ == "__main__":
    sys.exit(main()) 